﻿using UnityEngine;
using System.Collections;

public class FpsDetector : ConsoleComponent
{
    public float frequency = 0.5f; // The update frequency of the fps
    public int nbDecimal = 1; // How many decimal do you want to display

    private float accum = 0f; // FPS accumulated over the interval
    private int frames = 0; // Frames drawn over the interval
    private string sFPS = ""; // The fps formatted into a string.

    private float minFPS = 9999f;
    private float maxFPS = 0f;
    private float totalFrames = 0f;
    private int fpsLogCount = 0;

    public FpsDetector()
    {
        // Start recording fps
        DebugConsole.GetInstance().StartCoroutine(FPS());
    }

    public override void OnDrawing()
    {
        string fpsString = sFPS + " / L" + minFPS.ToString("#0.0") + " / H" + maxFPS.ToString("#0.0") + " FPS";
        GUIHelper.PrintShadowedText(fpsString, GUIHelper.RatioRect(0.005446143f, 0.9274625f, 0.1743715f, 0.06330022f));
    }

    public override void OnUpdate()
    {
        accum += Time.timeScale / Time.deltaTime;
        frames++;
    }

    IEnumerator FPS()
    {
        // Infinite loop executed every "frequency" seconds.
        while (true)
        {
            // Update the FPS
            float fps = accum / frames;
            totalFrames += fps;
            fpsLogCount++;
            if (fps < minFPS)
                minFPS = fps;
            if (fps > maxFPS)
                maxFPS = fps;

            sFPS = fps.ToString("f" + Mathf.Clamp(nbDecimal, 0, 10));

            accum = 0.0F;
            frames = 0;

            yield return new WaitForSeconds(frequency);
        }
    }
}
